package org.amos.server.modules.upms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.amos.core.basic.annotation.Log;
import org.amos.core.basic.constant.SystemConstant;
import org.amos.core.basic.utils.AmosUtils;
import org.amos.core.basic.utils.TreeUtils;
import org.amos.core.basic.utils.crud.WrapperBuilder;
import org.amos.server.modules.upms.dto.RegionDTO;
import org.amos.server.modules.upms.entity.Region;
import org.amos.server.modules.upms.entity.Role;
import org.amos.server.modules.upms.mapper.RegionMapper;
import org.amos.server.modules.upms.service.IRegionService;
import org.amos.server.modules.upms.vo.RegionVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 行政区划表 服务实现类
 * </p>
 *
 * @author liubt
 * @since 2022-11-10
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {

    @Override
    public List<RegionVO> selectTree(RegionDTO dto) {
        List<Region> regionList = baseMapper.selectList(new WrapperBuilder().build(dto));
        if (CollUtil.isEmpty(regionList)) {
            return new ArrayList<>();
        }
        List<RegionVO> originalList = AmosUtils.listCopy(regionList, RegionVO.class);
        return TreeUtils.generateTrees(originalList);
    }

    @Override
    @Log(value = "[更新行政区划信息]")
    public void saveOrUpdateRegion(RegionDTO dto) {
        super.saveOrUpdate(AmosUtils.copy(dto, Region.class));
    }

    @Override
    @Log(value = "[删除行政区划信息]")
    public void removeRegion(Set<Long> ids) {
        UpdateWrapper<Region> uw = new UpdateWrapper<>();
        uw.in(AmosUtils.toDbField(Region::getId), ids).set(AmosUtils.toDbField(Role::getIsDeleted), SystemConstant.SYS_DELETE_FLAG_ALREADY);
        super.update(uw);
    }
}
